package main

import (
	"fmt"
	cmap "github.com/orcaman/concurrent-map/v2"
	"github.com/zekroTJA/timedmap/v2"
	"log"
	"math/rand"
	"strconv"
	"time"
)

func main() {
	//testConcurrentMap()
	testTimedMap()
}

// testConcurrentMap
//
//	@Description: https://github.com/orcaman/concurrent-map 使用分片加锁的map
func testConcurrentMap() {
	m := cmap.New[string]()
	m.Set("key", "value")
	get, b := m.Get("key")
	fmt.Println(get, b)
	m.Remove("key")

	go func() {
		for {
			m.Set("key", strconv.Itoa(rand.Intn(10)))
		}
	}()

	go func() {
		for {
			println(m.Get("key"))
		}
	}()
	select {}
}

// timedMap
//
//	@Description: https://github.com/zekroTJA/timedmap 带有过期功能的map
func testTimedMap() {

	// Creates a new timed map which scans for
	// expired keys every 1 second
	tm := timedmap.New[string, int](1 * time.Second)

	// Add a key "hey" with the value 213, which should
	// expire after 3 seconds and execute the callback, which
	// prints that the key was expired
	tm.Set("hey", 213, 3*time.Second, func(v int) {
		log.Println("key-value pair of 'hey' has expired")
	})

	// Print key "hey" from timed map
	printKeyVal(tm, "hey")

	// Wait for 5 seconds
	// During this time the pool01-baseuse thread is blocked, the
	// key-value pair of "hey" will be expired
	time.Sleep(5 * time.Second)

	// Printing value of key "hey" wil lfail because the
	// key-value pair does not exist anymore
	printKeyVal(tm, "hey")
}

func printKeyVal(tm *timedmap.TimedMap[string, int], key string) {
	d, ok := tm.GetValue(key)
	if !ok {
		log.Println("data expired")
		return
	}

	log.Printf("%v = %d\n", key, d)
}
